package com.itany.corejava.day14;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class TestEditor implements ActionListener {

    private JFrame jf;
    private JMenuBar jmb;
    private JTextArea jta;

    private boolean wasSaved=true;
    private String filePath;


    public TestEditor() {
        jf=new JFrame();
        jmb=new JMenuBar();

        String[] jmLab={"文件","编辑","查看","帮助"};

        String[][] jmiLab={
                {"新建","打开","","保存","另存为","","退出"},
                {"撤销","","剪切","复制","粘贴","","查找","替换"},
                {},
                {"关于记事本"}
        };

        for (int i = 0; i < jmLab.length; i++) {

            JMenu jm=new JMenu(jmLab[i]);

            if("查看".equals(jmLab[i])){
                JMenu jm2=new JMenu("缩放");


                JMenuItem biggerJmi=new JMenuItem("放大");
                JMenuItem smallerJmi=new JMenuItem("缩小");


                biggerJmi.addActionListener(e->{
                    Font font=jta.getFont();
                    jta.setFont(font.deriveFont(font.getStyle(),font.getSize()+5));
                });

                smallerJmi.addActionListener(e->{
                    Font font=jta.getFont();
                    jta.setFont(font.deriveFont(font.getStyle(),font.getSize()-5));
                });

                jm2.add(biggerJmi);
                jm2.add(smallerJmi);

                jm.add(jm2);
                jmb.add(jm);
                continue;
            }






            for (int j = 0; j < jmiLab[i].length; j++) {
                if("".equals(jmiLab[i][j])){
                    jm.addSeparator();
                }else {
                    JMenuItem jmi = new JMenuItem(jmiLab[i][j]);
                    jmi.addActionListener(this);
                    jm.add(jmi);
                }
            }

            jmb.add(jm);

        }


        jta=new JTextArea(20,50);
    }

    private void init(){
        jf.setJMenuBar(jmb);
        JScrollPane jsp=new JScrollPane(jta);
        jf.add(jsp);
    }



    private void exit(){
        if(false==wasSaved) {
            int op=JOptionPane.showConfirmDialog(jf, "文件没有保存是否退出？", "确认退出", JOptionPane.YES_NO_CANCEL_OPTION);
            if(JOptionPane.YES_OPTION!=op){
                return;
            }
        }
        System.exit(0);
    }


    private void addEventHandler(){
        jf.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                exit();
            }
        });

        jta.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                System.out.println("TestEditor.insertUpdate");
                wasSaved=false;
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                System.out.println("TestEditor.removeUpdate");
                wasSaved=false;
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                System.out.println("TestEditor.changedUpdate");
                wasSaved=false;
            }
        });
    }


    public void show(){
        init();
        addEventHandler();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestEditor().show();
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd=e.getActionCommand();

        System.out.println(cmd);

        if("打开".equals(cmd)){
            FileDialog fd=new FileDialog(jf,"打开文件");
            fd.setFilenameFilter((dir,name)->name.endsWith(".txt"));
            fd.setVisible(true);
            if(fd.getFile()==null){
                return;
            }
            filePath=fd.getDirectory()+fd.getFile();

            try(BufferedReader br=new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(filePath),"utf-8"
                    )
            )){

                String s;

                jta.setText("");

                while((s=br.readLine())!=null){
                    jta.append(s+"\n");
                }

                wasSaved=true;

            }catch (Exception ex){
                JOptionPane.showMessageDialog(jf,"打开失败");
            }


        }

        if("保存".equals(cmd)){
            if(filePath==null){
                FileDialog fd=new FileDialog(jf,"另存为",FileDialog.SAVE);
                fd.setFilenameFilter((dir,name)->name.endsWith(".txt"));
                fd.setVisible(true);
                if(fd.getFile()==null){
                    return;
                }
                filePath=fd.getDirectory()+fd.getFile();
            }

            save();

            wasSaved=true;
        }

        if("另存为".equals(cmd)){
            FileDialog fd=new FileDialog(jf,"另存为",FileDialog.SAVE);
            fd.setFilenameFilter((dir,name)->name.endsWith(".txt"));
            fd.setVisible(true);
            if(fd.getFile()==null){
                return;
            }
            filePath=fd.getDirectory()+fd.getFile();

            save();

            wasSaved=true;

        }

        if("退出".equals(cmd)){
            exit();
        }

    }

    private void save(){
        try(PrintWriter pw=new PrintWriter(filePath,"utf-8")){

            pw.print(jta.getText());


        }catch (Exception e){
            JOptionPane.showMessageDialog(jf,"保存失败");
        }
    }
}
